package wangjg.android.common.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.util.Log;

public class LocalSocketDemo{
	private String name="test";
	private int bufferSize = 1024;
	
	private LocalSocket receiver;
	private LocalSocket sender;
	private LocalServerSocket lss;

	public LocalSocketDemo(String name) throws Exception {
		super();
		this.name = name;
		lss = new LocalServerSocket(name);
	}

	public void startup() {
		try {
			receiver = new LocalSocket();
			receiver.connect(new LocalSocketAddress("mytest"));
			receiver.setReceiveBufferSize(bufferSize);
			receiver.setSendBufferSize(bufferSize);
			
			sender = lss.accept();
			
			sender.setReceiveBufferSize(bufferSize);
			sender.setSendBufferSize(bufferSize);

			running = true;

			new Sender("sender-1",sender).start();
			new Receiver("receiver-1",receiver).start();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean running = false;

	class Sender extends Thread {
		private String name;
		private LocalSocket ls;

		public Sender(String name, LocalSocket ls) {
			this.name = name;
			this.ls = ls;
		}

		public void run() {
			try {
				OutputStream os = ls.getOutputStream();
				while (running) {
					byte[] buf = (name + " send.").getBytes();
					ls.setSendBufferSize(buf.length);
					ls.setReceiveBufferSize(buf.length);
					os.write(buf);
					os.flush();

					Thread.sleep(1000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					this.ls.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	class Receiver extends Thread {
		private String name;
		private LocalSocket ls;

		public Receiver(String name, LocalSocket ls) {
			this.name = name;
			this.ls = ls;
		}

		public void run() {
			try {
				InputStream is = this.ls.getInputStream();
				while (running) {
					int len = this.ls.getReceiveBufferSize();
					byte[] buf = new byte[len];
					is.read(buf);
					Log.i(this.name, "---" + new String(buf));
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					this.ls.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
